﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : PutInCard
//        description : 半成品/成品卡入库

//        created by XXX at  20150821
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using System.IO;
using System.Web;
using System.Text;


namespace CardLogistics.Web.MainPage.PutInCard.PutInCard
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.PutInCard.PutInCardData DAL = new DAL.PutInCard.PutInCardData();
        private static readonly CardLogistics.DAL.PutInCard.PutInCard_DetailData DetailDAL = new DAL.PutInCard.PutInCard_DetailData();
        private static readonly CardLogistics.DAL.CardRecordData CardDAL = new DAL.CardRecordData();
        private static DataTable DtDetails = null;//详细信息表
        string putInId = string.Empty; //子表外键Id
        protected Dictionary<string, string> CardTypeList = null;
        protected string isSubmit = "0";
        public static string TitleName;

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CREATEDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//制卡日期
                PUTINDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//入库日期
                CREATEUSER.Value = LoggedUser.USERFULLNAME;//制卡人默认为当前登录用户
                DtDetails = null;
                InitControl();
            }
        }
        #endregion

        #region 编辑时绑定值
        /// <summary>
        /// 编辑时绑定值
        /// </summary>
        public void InitControl()
        {
            TitleName = GetStatusInfo(0, "半成品/成品卡入库");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    tr_Details.Visible = tr_IC1.Visible = tr_IC2.Visible = true;
                    CardLogistics.Model.PutInCard.PutInCard pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    CardVERSION.Text = pData.VERSION;
                    OutStorageNo.Value = pData.OUTSTORAGENO;
                    hf_OutStorageId.Value = pData.OUTSTORAGEID;

                    DataTable dd = DetailDAL.GetInfoByPutInId(pData.ID);
                    rptDetailList.DataSource = dd;
                    //根据卡号升序排列
                    dd.DefaultView.Sort = "CardId ASC";
                    rptDetailList.DataBind();

                    btn_Add.Visible = btn_Submit.Visible = false;

                    if (pData.IsSubmit == 0 || pData.IsSubmit == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(pData.IsSubmit, "半成品/成品卡入库");
                    isSubmit = pData.IsSubmit.ToString();

                }
            }
            else
            {
                PUTINNO.Value = GetBillNumber("半成品/成品入库");
            }

        }
        #endregion

        #region 创建临时 DtDetails
        /// <summary>
        /// 创建临时 DtDetails  
        /// </summary>
        private void CreateDtd()
        {
            DtDetails = new DataTable();
            DtDetails.Columns.Add("DevId");
            DtDetails.Columns.Add("OprId");
            DtDetails.Columns.Add("IssDate");
            DtDetails.Columns.Add("ExpDate");
            DtDetails.Columns.Add("CardId");
            DtDetails.Columns.Add("CardSSN");
            DtDetails.Columns.Add("CardCSN");
            DtDetails.Columns.Add("CardType");
            DtDetails.Columns.Add("ChildCardType");
            DtDetails.Columns.Add("CardMac");
            DtDetails.Columns.Add("FgvAmt");
            DtDetails.Columns.Add("InitAmt");
            DtDetails.Columns.Add("IniFlag");
            DtDetails.Columns.Add("Reserved");
            DtDetails.Columns.Add("Putinid");
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(5, result.Split(',')[1]);//5半成品/成品入库
                    InsertLog("保存并提交半成品/成品卡入库信息,入库单号:" + PUTINNO.Value);
                }
                else
                    InsertLog("保存半成品/成品卡入库信息,入库单号:" + PUTINNO.Value);
                ReturnListInfo();
            }
            else if (result.Split(',')[1] == "-2")
            {
                ShowMessageBox("请先选择入库文件!");
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 半成品/成品卡入库主表信息
        /// <summary>
        /// 半成品/成品卡入库主表信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            //----------主表实体------------//
            string result = string.Empty;
            CardLogistics.Model.PutInCard.PutInCard model = new CardLogistics.Model.PutInCard.PutInCard();
            model = GetWebControls<CardLogistics.Model.PutInCard.PutInCard>(this.Page);
            if (RECNUM.Text == "Label" || RECNUM.Text == "")
            {
                result = "err,-2"; //没有选择入库的文件
            }
            else
            {
                GetDtDetails(); //修改列表
                DataTable dttmp = DtDetails;

                model.PUTINDATE = Convert.ToDateTime(PUTINDATE.Value);//入库日期
                model.CREATEDATE = Convert.ToDateTime(CREATEDATE.Value);//制卡日期
                model.VERSION = CardVERSION.Text; //版本号
                model.CARDKIND = CARDKIND.Text; //卡类型
                model.BATCHID = BATCHID.Text;//批次号
                model.CARDBEGINSSN = CARDBEGINSSN.Text;//文件初始卡号
                model.CARDENDSSN = CARDENDSSN.Text; //文件结束卡号
                model.RECNUM = RECNUM.Text; //记录总数
                model.IsSubmit = issubmit;//0 未提交 1 待审核 2 审核中 3 驳回 4 审核不通过 5审核通过
                model.OUTSTORAGEID = hf_OutStorageId.Value;

                if (IsEdit)
                {
                    model.ID = Request.QueryString["id"];
                    result = DAL.Update(model, DtDetails);
                }
                else
                {
                    result = DAL.Add(model, DtDetails);
                    if (result.Split(',')[0] == "ok")
                    {
                        ChgBillNumber("半成品/成品入库");
                    }
                }
            }
            return result.ToString();
        }
        #endregion

        #region 修改时获取Repeater列表方法
        /// <summary>
        /// 修改时获取Repeater列表方法
        /// </summary>
        private void GetDtDetails()
        {
            DtDetails = new DataTable();
            CreateDtd();
            DataRow di = DtDetails.NewRow();
            foreach (RepeaterItem ri in this.rptDetailList.Items)
            {
                di = DtDetails.NewRow();
                di["DevId"] = ((Label)ri.FindControl("lbl_DevId")).Text;//发卡机编号
                di["OprId"] = ((Label)ri.FindControl("lbl_OprId")).Text;//发卡操作员编号
                di["IssDate"] = ((Label)ri.FindControl("lbl_IssDate")).Text;//发卡日期 YYYYMMDD
                di["ExpDate"] = ((Label)ri.FindControl("lbl_ExpDate")).Text;//有效日期 YYYYMMDD
                di["CardId"] = ((Label)ri.FindControl("lbl_CardId")).Text;//卡面号
                di["CardSSN"] = ((Label)ri.FindControl("lbl_CardSSN")).Text;//卡号
                di["CardCSN"] = ((Label)ri.FindControl("lbl_CardCSN")).Text;//CSN唯一代码
                di["CardType"] = ((Label)ri.FindControl("lbl_CardType")).Text;//主卡类型标志
                di["ChildCardType"] = ((Label)ri.FindControl("lbl_ChildCardType")).Text;//子卡类型标志
                di["CardMac"] = ((Label)ri.FindControl("lbl_CardMac")).Text;//卡校验值
                di["FgvAmt"] = ((Label)ri.FindControl("lbl_FgvAmt")).Text;//押金（单位：分）
                di["InitAmt"] = ((Label)ri.FindControl("lbl_InitAmt")).Text; //充值后余额（单位：分）
                di["IniFlag"] = ((Label)ri.FindControl("lbl_IniFlag")).Text;//卡启用标志 00：未启用卡； 01：已启用卡
                DtDetails.Rows.Add(di);
            }
        }
        #endregion

        #region 导入发卡文件
        /// <summary>
        /// 导入发卡文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImport_Click(object sender, EventArgs e)
        {
            HttpPostedFile file = this.FileUpload1.PostedFile;
            //if (File.Exists(Server.MapPath("~/MainPage/File/PutInCardFile/" + FileUpload1.FileName)))
            //{
            //    ShowMessageBox("该文件已导入!");
            //    return;
            //}
            string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName); //获取扩展名
            string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); //获取文件名（不包括扩展名）
            string filePath = Server.MapPath("~/MainPage/File/PutInCardFile/" + fileName + DateTime.Now.ToString("yyyyMMddHHmmss") + Extension);
            file.SaveAs(filePath);
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));

            if (DtDetails == null)
            {
                CreateDtd();
            }
            DtDetails.Rows.Clear();
            tr_Details.Visible = tr_IC1.Visible = tr_IC2.Visible = true;
            int i = 0;//记录行数
            string startNo = "";//开始卡号
            string endNo = ""; //结束卡号
            DataTable DtBkCK = null;//白卡出库明细
            while (!sr.EndOfStream)
            {
                try
                {
                    string fvalue = sr.ReadLine();
                    i++;
                    if (i==1 && fvalue.Trim().Length != 55)
                    {
                        ShowMessageBox("导入文件中第1行格式有误，请核对！");
                        return;
                    }
                    if (fvalue.Trim().Length == 55)
                    {
                        CardVERSION.Text = fvalue.Substring(0, 2);//版本号 当前版本是10
                        CARDKIND.Text = fvalue.Substring(2, 2);//卡类型 01－CPU卡 03－Mifire卡
                        BATCHID.Text = fvalue.Substring(4, 14);//制卡批次号  J0001200600001
                        CARDBEGINSSN.Text = fvalue.Substring(18, 16);//文件初始卡号
                        CARDENDSSN.Text = fvalue.Substring(34, 16);//文件结束卡号
                        RECNUM.Text = fvalue.Substring(50, 5);//记录总数

                        startNo = (CARDBEGINSSN.Text).Substring(8, 8); //文件开始卡号
                        endNo = (CARDENDSSN.Text).Substring(8, 8);//文件结束卡号

                        DtBkCK = CardDAL.ISBKCK(hf_OutStorageId.Value, startNo, endNo);
                        if (DtBkCK == null || DtBkCK.Rows.Count == 0)
                        {
                            ShowMessageBox("起始卡号至结束卡号不在当前选择的出库单中！");
                            tr_IC1.Visible = false;
                            tr_IC2.Visible = false;
                            CardVERSION.Text = null;
                            CARDKIND.Text = null;
                            BATCHID.Text = null;
                            CARDBEGINSSN.Text = null;
                            CARDENDSSN.Text = null;
                            RECNUM.Text = null;
                            fs.Flush(); //释放流
                            fs.Close();//关闭流
                            FileInfo fi = new FileInfo(filePath);
                            fi.Delete(); //删除导入失败的文件
                            return;
                        }
                    }
                    else if (fvalue.Trim().Length == 111)
                    {
                        DataRow di = DtDetails.NewRow();
                        di["DevId"] = fvalue.Substring(0, 9);//发卡机编号
                        di["OprId"] = fvalue.Substring(9, 9);//发卡操作员编号
                        di["IssDate"] = fvalue.Substring(18, 8);//发卡日期 YYYYMMDD
                        di["ExpDate"] = fvalue.Substring(26, 8);//有效日期 YYYYMMDD
                        di["CardId"] = fvalue.Substring(34, 16);//卡面号
                        di["CardSSN"] = fvalue.Substring(50, 16);//卡号
                        di["CardCSN"] = fvalue.Substring(66, 16);//CSN唯一代码
                        di["CardType"] = fvalue.Substring(82, 2);//主卡类型标志
                        di["ChildCardType"] = fvalue.Substring(84, 2);//子卡类型标志
                        di["CardMac"] = fvalue.Substring(86, 8);//卡校验值
                        di["FgvAmt"] = fvalue.Substring(94, 5);//押金（单位：分）
                        di["InitAmt"] = fvalue.Substring(99, 6); //充值后余额（单位：分）
                        di["IniFlag"] = fvalue.Substring(105, 2);//卡启用标志 00：未启用卡； 01：已启用卡

                        string cardId = fvalue.Substring(34, 16).Substring(8, 8); //卡面号

                        DtDetails.Rows.Add(di);
                        if (DtDetails != null)
                        {
                            //判断卡号是否重复
                            if (DtDetails.Select("CardSSN=" + di["CardSSN"]).Length > 1)
                            {
                                ShowMessageBox("导入文件中第" + i + "行卡号[" + cardId + "]重复，请核对！");
                                return;
                            }
                            if (DtBkCK.Select(" cardno='" + cardId + "'").Length == 0)
                            {
                                ShowMessageBox("导入文件中第" + i + "行卡号[" + cardId + "]在白卡出库单中不存在，请核对！");
                                return;
                            }
                        }
                    }
                }
                catch
                { }
            }
            rptDetailList.DataSource = DtDetails;
            rptDetailList.DataBind();
        }
        #endregion

        #region 删除导入明细
        protected void Ibtn_Del_Click(object sender, EventArgs e)
        {
            string temp = (sender as ImageButton).CommandArgument.ToString();
            DtDetails = new DataTable();
            CreateDtd();
            DataRow di = DtDetails.NewRow();
            foreach (RepeaterItem ri in this.rptDetailList.Items)
            {
                if (((Label)ri.FindControl("lbl_CardId")).Text.Trim() != temp.Trim())
                {
                    di = DtDetails.NewRow();
                    di["DevId"] = ((Label)ri.FindControl("lbl_DevId")).Text;//发卡机编号
                    di["OprId"] = ((Label)ri.FindControl("lbl_OprId")).Text;//发卡操作员编号
                    di["IssDate"] = ((Label)ri.FindControl("lbl_IssDate")).Text;//发卡日期 YYYYMMDD
                    di["ExpDate"] = ((Label)ri.FindControl("lbl_ExpDate")).Text;//有效日期 YYYYMMDD
                    di["CardId"] = ((Label)ri.FindControl("lbl_CardId")).Text;//卡面号
                    di["CardSSN"] = ((Label)ri.FindControl("lbl_CardSSN")).Text;//卡号
                    di["CardCSN"] = ((Label)ri.FindControl("lbl_CardCSN")).Text;//CSN唯一代码
                    di["CardType"] = ((Label)ri.FindControl("lbl_CardType")).Text;//主卡类型标志
                    di["ChildCardType"] = ((Label)ri.FindControl("lbl_ChildCardType")).Text;//子卡类型标志
                    di["CardMac"] = ((Label)ri.FindControl("lbl_CardMac")).Text;//卡校验值
                    di["FgvAmt"] = ((Label)ri.FindControl("lbl_FgvAmt")).Text;//押金（单位：分）
                    di["InitAmt"] = ((Label)ri.FindControl("lbl_InitAmt")).Text; //充值后余额（单位：分）
                    di["IniFlag"] = ((Label)ri.FindControl("lbl_IniFlag")).Text;//卡启用标志 00：未启用卡； 01：已启用卡
                    DtDetails.Rows.Add(di);
                }
            }
            rptDetailList.DataSource = DtDetails;
            //根据卡号升序排列
            DtDetails.DefaultView.Sort = "CardId ASC";
            rptDetailList.DataBind();
        }
        #endregion
    }
}